package com.example.blog.common.Utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class JWTUtils {
    //用于产生密钥的字符串
    private final static String secret="wJnc1PiDvmImWFaYUNphrjMuJKEiyJ/p/vnL5vgnhO4=";
    //过期时间一天
    private final static long EXPIRATIONTIME=7*24*60*60*1000;
    //产生安全密钥
    private final static Key key=Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));

    //产生令牌
    public static String jwt(Map<String,Object>map){
        String compact = Jwts.builder().setClaims(map)
                .setIssuedAt(new Date())//设置签发时间
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
                .signWith(key)//签名算法
                .compact();
        return compact;
    }

    //检验令牌
    public static Claims parseJwt(String jwt){
        if(!StringUtils.hasLength(jwt)){
            return null;
        }
        JwtParserBuilder jwtParserBuilder = Jwts.parserBuilder().setSigningKey(key);
        //解析token
        Claims body = null;
        try {
            body = jwtParserBuilder.build().parseClaimsJws(jwt).getBody();
        } catch (Exception e) {
            log.info("解析令牌失败jwt:{}"+e);
        }
        return body;
    }
//eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoibGlzaSIsImlkIjoyLCJpYXQiOjE3NTM1ODE2NzEsImV4cCI6MTc1NDE4NjQ3MX0.PkmoW5tHVV02gb6k1iT3EQSDYCQdgCg9mqBraGM78UY
    //获取token中用户ID
    public static Integer getUserId(String jwtToken){
        Claims claims = JWTUtils.parseJwt(jwtToken);
        if(claims!=null){
            Map<String,Object>map=new HashMap<>(claims);
            return (Integer) map.get(jwtToken);
        }
        return null;
    }

    public static void main(String[] args) {
        Claims claims = parseJwt("eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoibGlzaSIsImlkIjoyLCJpYXQiOjE3NTM1ODE2NzEsImV4cCI6MTc1NDE4NjQ3MX0.PkmoW5tHVV02gb6k1iT3EQSDYCQdgCg9mqBraGM78UY");
        System.out.println(claims);
    }
}
